#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
调试排列5预测结果全是0的问题
分析模型预测的每个步骤
"""

import sys
import os
import torch
import numpy as np

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)

def debug_plw_prediction():
    """调试排列5预测的每个步骤"""
    print(" 调试排列5预测结果全是0的问题")
    print("=" * 60)
    
    try:
        from lottery_predictor_app import load_resources_pytorch, PLWPredictor, process_predictions
        
        # 1. 测试模型加载
        print("[INFO] 步骤1: 加载排列5模型")
        
        model_path = "./scripts/plw/plw_model.pth"
        if not os.path.exists(model_path):
            print(f"[ERROR] 模型文件不存在: {model_path}")
            return False
        
        try:
            plw_model, _, scaler_X = load_resources_pytorch("plw")
            print("[INFO] 模型加载成功")
            print(f"📝 模型类型: {type(plw_model)}")
            print(f"📝 模型参数数量: {sum(p.numel() for p in plw_model.parameters())}")
        except Exception as e:
            print(f"[ERROR] 模型加载失败: {e}")
            return False
        
        # 2. 测试数据获取
        print("\n[INFO] 步骤2: 获取输入数据")
        
        data_file = "./scripts/plw/plw_history.csv"
        if not os.path.exists(data_file):
            data_file = "./scripts/plw/plw_correct_data.csv"
        
        predictor = PLWPredictor(data_file, 5)
        recent_data = predictor.features[-1]
        
        print(f"[INFO] 输入数据获取成功")
        print(f" 数据形状: {recent_data.shape}")
        print(f" 数据类型: {type(recent_data)}")
        print(f" 数据范围: {recent_data.min().item():.3f} - {recent_data.max().item():.3f}")
        print(f" 前5行数据:\n{recent_data}")
        
        # 3. 测试模型预测（详细分析）
        print("\n[INFO] 步骤3: 详细分析模型预测")
        
        # 准备输入数据
        input_data = recent_data.unsqueeze(0)  # 添加batch维度
        print(f" 模型输入形状: {input_data.shape}")
        print(f" 模型输入数据:\n{input_data}")
        
        # 使用模型进行预测
        plw_model.eval()
        with torch.no_grad():
            try:
                predictions = plw_model(input_data)
                print(f"[INFO] 模型预测成功")
                print(f" 预测结果类型: {type(predictions)}")
                print(f" 预测结果: {predictions}")
                
                if isinstance(predictions, list):
                    print(f" 预测列表长度: {len(predictions)}")
                    if len(predictions) > 0:
                        predicted_sequence = predictions[0]
                        print(f" 第一个预测序列: {predicted_sequence}")
                        print(f" 预测序列类型: {type(predicted_sequence)}")
                        print(f" 预测序列长度: {len(predicted_sequence) if hasattr(predicted_sequence, '__len__') else 'N/A'}")
                        
                        # 测试process_predictions函数
                        print(f"\n[INFO] 步骤4: 测试process_predictions函数")
                        try:
                            processed_result = process_predictions(predicted_sequence, None, "plw")
                            print(f"[INFO] process_predictions成功")
                            print(f" 处理后结果: {processed_result}")
                            print(f" 结果类型: {type(processed_result)}")
                            
                            # 分析为什么全是0
                            if all(num == 0 for num in processed_result):
                                print("[WARNING] 发现问题：处理后结果全是0")
                                print(" 分析原因：")
                                print(f"   - 原始预测序列: {predicted_sequence}")
                                print(f"   - process_predictions输入: {predicted_sequence[:5]}")
                                
                                # 手动执行process_predictions的逻辑
                                manual_result = []
                                for i, num in enumerate(predicted_sequence[:5]):
                                    processed_num = min(max(int(num), 0), 9)
                                    print(f"   - 位置{i}: {num} -> {processed_num}")
                                    manual_result.append(processed_num)
                                print(f"   - 手动处理结果: {manual_result}")
                                
                            else:
                                print("[INFO] 处理后结果正常")
                                
                        except Exception as process_error:
                            print(f"[ERROR] process_predictions失败: {process_error}")
                            import traceback
                            print(traceback.format_exc())
                            
                elif isinstance(predictions, torch.Tensor):
                    print(f" 预测张量形状: {predictions.shape}")
                    print(f" 预测张量数据:\n{predictions}")
                    
                    # 如果是张量，尝试转换为列表
                    if predictions.dim() >= 2:
                        predicted_sequence = predictions[0].tolist()
                        print(f" 转换为列表: {predicted_sequence}")
                        
                        # 测试process_predictions
                        try:
                            processed_result = process_predictions(predicted_sequence, None, "plw")
                            print(f"[INFO] 张量转列表后process_predictions成功: {processed_result}")
                        except Exception as e:
                            print(f"[ERROR] 张量转列表后process_predictions失败: {e}")
                    
                else:
                    print("[WARNING] 未知的预测结果格式")
                    
            except Exception as pred_error:
                print(f"[ERROR] 模型预测失败: {pred_error}")
                import traceback
                print(traceback.format_exc())
                return False
        
        # 4. 对比确定性预测
        print("\n[INFO] 步骤5: 对比确定性预测")
        np.random.seed(100)
        deterministic_result = np.random.randint(0, 10, 5).tolist()
        print(f"确定性预测结果: {deterministic_result}")
        
        print("\n[INFO] 调试完成！")
        return True
        
    except Exception as e:
        print(f"[ERROR] 调试过程出现异常: {e}")
        import traceback
        print(traceback.format_exc())
        return False

if __name__ == "__main__":
    debug_plw_prediction()